package handle

import (
	"fmt"
	"log"
	"strconv"

	"github.com/google/uuid"
	"github.com/hashicorp/consul/api"
)

var (
	serviceID string
)

func InitConsul() {
	serviceID = fmt.Sprintf("%s-%s", cfg.AppName, uuid.New().String())
	port, err := strconv.Atoi(ApolloConfigCache.GetValue("port"))
	if err != nil {
		log.Printf("port error : %v", err)
	}

	config := api.DefaultConfig()
	config.Address = ApolloConfigCache.GetValue("consul-address")

	client, err := api.NewClient(config)
	if err != nil {
		log.Printf("consul client error : %v", err)
		return
	}

	// 创建注册到consul的服务到
	registration := &api.AgentServiceRegistration{
		ID:      serviceID,
		Name:    cfg.AppName,
		Port:    port,
		Tags:    []string{cfg.AppName},
		Address: getLocalIP(),
		Check: &api.AgentServiceCheck{
			HTTP:                           fmt.Sprintf("http://%s:%d/health", getLocalIP(), port),
			Timeout:                        "5s",
			Interval:                       "5s",
			DeregisterCriticalServiceAfter: "30s",
		},
	}

	// 注册服务到consul
	err = client.Agent().ServiceRegister(registration)

	if err != nil {
		log.Printf("consul register error : %v", err)
		return
	}
}

func DeregisterConsulService() {
	config := api.DefaultConfig()
	config.Address = ApolloConfigCache.GetValue("consul-address")

	client, err := api.NewClient(config)
	if err != nil {
		log.Printf("consul client error : %v", err)
		return
	}

	err = client.Agent().ServiceDeregister(serviceID)
	if err != nil {
		log.Printf("consul deregister error : %v", err)
		return
	}
}

func getLocalIP() string {
	// addrs, _ := net.InterfaceAddrs()
	// for _, addr := range addrs {
	// 	if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
	// 		if ip := ipnet.IP.To4(); ip != nil {
	// 			return ip.String()
	// 		}
	// 	}
	// }
	return "172.25.240.1"
}
